const path = require('path')
const Koa = require('koa2');

const cors = require('koa-cors');
const bodyParser = require('koa-bodyparser');
const koaStatic = require('koa-static')
const koaViews = require('koa-views')
// const jwt = require('jsonwebtoken')
const routes = require('./routers')
const compress = require('koa-compress')
// 日志模块
const log4js = require('./utils/logger')
const config = require('./config')
console.log(log4js, '==log4js==')
require('./db');

const app = new Koa();

app.use(koaStatic(
  path.join(__dirname , './public')
)) // 设置静态文件
//模板
app.use(koaViews(path.resolve(__dirname,'./public')))

app.use(cors({
    origin: 'http://localhost:8080',
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
})
); // 设置跨域


app.use(bodyParser({
  formLimit: '1mb'
})) // ctx body 中间件

app.use(compress({
  threshold: 2048
}))
// logger
app.use(async(ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}`)
  log4js.resLogger(ctx, ms)
})

routes(app)
app.on('error', (err, ctx) => {
  log4js.errLogger(ctx, err)
})
app.listen(config.port, () => {
  console.log('listen in localhost:' + config.port)
}) // 监听端口